using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.Billing;
using RBAC.Interstructrue;
using RBAC.Domain.SalesManage;
using System;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement.Billing
{
    /// <summary>
    /// 删除开票通知单处理程序
    /// </summary>
    public class DeleteBillingNoticeHandler : IRequestHandler<DeleteBillingNoticeCommand, APIResult<int>>
    {
        private readonly RBACDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public DeleteBillingNoticeHandler(RBACDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 处理逻辑删除开票通知单请求
        /// </summary>
        /// <param name="request">删除命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<APIResult<int>> Handle(DeleteBillingNoticeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找开票通知单
                var billingNotice = await _context.BillingAccountings
                    .FirstOrDefaultAsync(b => b.Id == request.Id, cancellationToken);

                if (billingNotice == null)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "未找到指定的开票通知单"
                    };
                }

                // 检查是否已经删除
                if (billingNotice.IsDeleted)
                {
                    return new APIResult<int>
                    {
                        Code = APIEnums.Fail,
                        Msg = "该开票通知单已被删除"
                    };
                }

                // 执行逻辑删除：修改删除标识
                billingNotice.IsDeleted = true;

                // 保存更改
                var result = await _context.SaveChangesAsync(cancellationToken);

                return new APIResult<int>
                {
                    Code = APIEnums.Success,
                    Msg = "删除成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = $"删除失败：{ex.Message}"
                };
            }
        }
    }
}